import { useEffect, useState, useRef, useCallback } from "react";
import { View } from "@tarojs/components";
import { FC } from "@tarojs/taro";
import { DynamicColors } from "@/utils/DarkMode";
import CircleProgress from "@/components/CircleProgress";

interface IProps {
  start: boolean; // 是否开始
  timeout: number; //超时时间，单位毫秒
  finish: boolean; // 是否完成
  showReact?: boolean;
}

const maxProgress = 95;

// 设置超时时间，会自动有一个假的进度前进，直到超时
const TimeLoading: FC<IProps> = ({ start, timeout, finish, showReact }) => {
  const [progress, setProgress] = useState(0);
  const timerRef = useRef<any>(null);
  const progressRef = useRef(progress);

  useEffect(() => {
    progressRef.current = progress;
  }, [progress])

  const endTimer = useCallback(() => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  }, []);

  const timerAdd = useCallback(() => {
    // 不要到100%，除非是finsh为true
    if (progressRef.current < maxProgress) {
      setProgress(progressRef.current + 1);
    } else {
      endTimer();
    }
  }, [endTimer]);

  const startTimer = useCallback(() => {
    endTimer();
    timerRef.current = setInterval(timerAdd, timeout / maxProgress);
  }, [endTimer, timerAdd, timeout])

  useEffect(() => {
    if (start) {
      startTimer();
    }
    return () => {
      endTimer();
    }
  }, [start])

  useEffect(() => {
    if (finish) {
      setProgress(100);
    }
  }, [finish])

  return (
    <View>
      <CircleProgress width={30} progress={progress} tintColor={DynamicColors.tintColor.value} showReact={showReact} />
    </View>
  );
};

export default TimeLoading;
